import store from '../store/index.js'
const resInfo = {
	isRes: true,
	resTrue: function() {
		this.isRes = true
	},
	resFlase: function() {
		this.isRes = false
	}
}

const navInfo = {
	navBarHeight: '',
	scrollwidth: ''
}
uni.getSystemInfo({
	success: res => {
		navInfo.navBarHeight = res.statusBarHeight
		navInfo.scrollwidth = res.windowWidth
	}
})
const tui = {
	goBack: function() {
		let canNavBack = getCurrentPages();
		if (canNavBack && canNavBack.length > 1) {
			uni.navigateBack({
				delta: 1
			});
		} else {
			history.back();
		}
	},
	navBarHeight: navInfo.navBarHeight,
	scrollwidth: navInfo.scrollwidth,
	toast: function(text, duration, position, success) {
		uni.showToast({
			title: text,
			duration: duration || 2000,
			position: position || 'center',
			icon: success ? 'success' : 'none'

		})
	},
	//处理图片链接
	handleUrl: function(url) {
		if (url != 'null' && url != null && url != undefined && url != 'undefined' && url != '') {
			return `https://postrings.oss-accelerate.aliyuncs.com/${url}`
		}
		return '/static/setting/default_avatar.png'
	},
	uploadFile: function(src) {
		const that = this
		uni.showLoading({
			title: '请稍候...'
		})
		return new Promise((resolve, reject) => {
			const uploadTask = uni.uploadFile({
				// url:'http://youni.cool/api/public/upload',
				url: 'https://postrings.lotaoup.com/api/upload/avatar',
				filePath: src,
				name: 'image',
				success: function(res) {
					uni.hideLoading()
					let d = JSON.parse(res.data)
					if (d.code === 0) {
						resolve(d)
					} else {
						that.toast(res.message)
					}
				},
				fail: function(res) {
					reject(res)
					uni.hideLoading()
					that.toast(res.message)
				}
			})
			uploadTask.onProgressUpdate(res => {
				console.log('上传进度', res.progress);
			});
		})
	},
	toFixed: function(num,decimal) {
	    num = num.toString();
	    let index = num.indexOf('.');
	    if (index !== -1) {
	        num = num.substring(0, decimal + index + 1)
	    } else {
	        num = num.substring(0)
	    }
	    return parseFloat(num).toFixed(decimal)
	},
	filterCount: function(val){
		let count = parseFloat(val)
		if(count >= 10000){
			let num = count / 10000
			return tui.accMul(tui.toFixed(num,1),10) + 'K'
		}
		return count
	},
	precision: function(val, number, max = 999999999){
		if (parseFloat(val) >= 0) {
			//判断是否负数
			let index_k = val.indexOf('-')
			//判断是否小数
			let index_j = val.indexOf('.')
			if (index_k != -1) {
				//如果是负数则直接取绝对值
				return Math.abs(val) + ''
				//如果是正数并且大于50000则设置为5000
			} else if (val - max > 0) {
				return max + ''
			} else {
				//如果连续000000则为0
				if (index_j == -1 && parseFloat(val) == 0) {
					return '0'
				}
				//如果是小数则只保留6位小数
				if (index_j > 0 && (val.length - index_j) > (number + 1)) {
					// uni.$u.toast(`数字精确小数点后${number}位`)
					return val.slice(0, index_j + (number + 1))
				}
				return val
			}
		} else {
			return Math.abs(val) + ''
		}
	},
	//获取用户信息
	getUserInfo: function() {
		store.dispatch('auth/user').then(res => {})
	},
	//获取资产列表
	getWallet() {
		store.dispatch('wallet/wallet').then(res => {})
	},
	//获取网路列表
	getNetworks(){
		store.dispatch('public/networks').then(res=>{})
	},
	//获取模版类型
	getMoldsType(){
		store.dispatch('user/moldsTypes').then(res=>{})
	},
	//绑定推送
	bindPush() {
		let info = plus.push.getClientInfo()
		store.dispatch('user/userUpdate', {
			client_id: info.clientid
		}).then(res => {})
	},
	//减法消除浮点
	accSub(arg1, arg2) {
	    var r1, r2, m, n;
	    try { r1 = arg1.toString().split(".")[1].length } catch (e) { r1 = 0 }
	    try { r2 = arg2.toString().split(".")[1].length } catch (e) { r2 = 0 }
	    m = Math.pow(10, Math.max(r1, r2)); //last modify by deeka //动态控制精度长度
	    n = (r1 >= r2) ? r1 : r2;
	    return ((arg1 * m - arg2 * m) / m).toFixed(n);
	},
	//乘法
	accMul(arg1, arg2) {
	    if (arg1 === '') {
	      return ''
	    }
	    var m = 0,
	        s1 = arg1.toString(),
	        s2 = arg2.toString();
	    try {  m += s1.split(".")[1].length } catch (e) {}
	    try {  m += s2.split(".")[1].length } catch (e) {}
	    return Number(s1.replace(".", "")) * Number(s2.replace(".", "")) / Math.pow(10, m)
	},
	//h5生成随机数
	generateMixed(n) {
		var chars = ['0','1','2','3','4','5','6','7','8','9','A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z'];
	    var res = "";
	    for(var i = 0; i < n ; i ++) {
	        var id = Math.ceil(Math.random()*35);
	        res += chars[id];
	    }
	    return res
	},
	getDeviceMac() {
		//获取本机Mac地址
		var deviceMac = '';
		var net = plus.android.importClass('java.net.NetworkInterface');
		var wl0 = net.getByName('wlan0');
		var macByte = wl0.getHardwareAddress();
		deviceMac = '';
		for (var i = 0; i < macByte.length; i++) {
			var tmp = '';
			var num = macByte[i];
			if (num < 0) {
				tmp = (255 + num + 1).toString(16);
			} else {
				tmp = num.toString(16);
			}
			if (tmp.length == 1) {
				tmp = '0' + tmp;
			}
			deviceMac += tmp;
		}
		return deviceMac
	}
}
const Base64 = {
	//加密
	encode(str) {
		if (str === undefined || str === "" || str === null) {
			return str;
		}
		return btoa(encodeURIComponent(str).replace(/%([0-9A-F]{2})/g,
			function toSolidBytes(match, p1) {
				return String.fromCharCode('0x' + p1);
			}));
	},
	//解密
	decode(str) {
		if (str === undefined || str === "" || str === null) {
			return str;
		}
		return decodeURIComponent(atob(str).split('').map(function(c) {
			return '%' + ('00' + c.charCodeAt(0).toString(16)).slice(-2);
		}).join(''));
	}
}

export {
	resInfo,
	navInfo,
	tui,
	Base64
}
